<template >
  <!-- 服务管理 -->
  <div class="innerPageTable-box-OneTwo value-set-list-wrap innerPageTable-out-flex">
    <!-- 搜索区域 -->
    <SelfAdaption>
      <Form
        :model="searchForm"
        ref="serviceForm"
        slot="adaption-bar"
        label-position="top"
        class="ivu-form-no-margin-bottom"
        inline
      >
         <Form-item label="大类:">
          <Select v-model="searchForm.stype" clearable>
            <Option @click.native="stypeChange(item)" v-for="item in categoryInitiatives" :value="item.key" :key="item.key">{{
              item.value
            }}</Option>
          </Select>
        </Form-item>

         <Form-item label="小类:">
          <Select v-model="searchForm.mtype" clearable>
            <Option v-for="item in detailsInitiatives" :value="item.key" :key="item.key">{{
              item.value
            }}</Option>
          </Select>
        </Form-item>

        <Form-item label="重点任务:">
          <Input
            clearable
            type="text"
            v-model.trim="searchForm.highTask"
            :placeholder="'请输入'"
            @on-enter="searchValueSet"
          ></Input>
        </Form-item>

        <Form-item label="责任单位:">
          <Select filterable v-model="searchForm.dpart" clearable multiple>
            <Option @click.native="codeChange(item)" v-for="item in this.departList" :value="item.key" :key="item.key">{{
              item.value
            }}</Option>
          </Select>
        </Form-item>

        <Form-item label="完成状态:">
          <Select v-model="searchForm.isFinished" clearable>
            <Option v-for="item in completeStatus" :value="item.key" :key="item.key">{{
              item.value
            }}</Option>
          </Select>
        </Form-item>

        <!-- 查询\重置按钮 -->
        <Form-item prop="button" class="search-solt-btn">
          <RPButton optType="search" ref='search' @click="searchValueSet()" />
        </Form-item>
      </Form>
    </SelfAdaption>

    <InnerPageTable ref="valueSetTable" :config="pageTableConfig" v-if='showTable'>
      <div slot="table-bar" v-if="hasPermission('GROUP_IMPLEMENT_ADMIN')">
        <RPButton optType="create" type="info" text="导出" @click="batchExport" />
        <RPButton :disabled="createDisabled" optType="create" type="info" text="新增重点任务" @click="goPlanCreatePage"/>
        <RPButton :disabled="initDisabled" :optType="initDisabled ? 'batch' :'create'" text="初始化" @click="initTask"/>
        <RPButton :disabled="initDisabled" :optType="initDisabled ? 'batch' :'create'" type="info" text="发起任务" @click="startTask"/>
        <RPButton :disabled="submitDisabled" optType="create" type="info" text="提交汇总审批" @click="summaryAppSubmit"/>
        <!-- 为了不让最后一个按钮的样式有问题，特别多加一个无意义按钮 -->
        <RPButton optType="create" type="info" text="删除" @click="batchDel"/>
        <RPButton optType="create" type="info" text="" style="display:none"/>
      </div>

      <div slot="table-bar" v-else>
        <RPButton optType="create" type="info" text="导出" @click="batchExport" />
        <RPButton :disabled="submitDisabled" optType="create" type="info" text="批量提交" @click="batchSubmit"/>
        <RPButton optType="create" type="info" text="" style="display:none"/>
      </div>
    </InnerPageTable>
  </div>
</template>

<script>
import { groupPlanDataColumns, groupColumnList } from './columns'
import { departList,importist,completeStatus,PROCESS_STATUS_MAP } from './dataConfig.js'
import uploadFile from './uploadFile'
import groupPlanEditAndDetail from './groupPlanEditAndDetail.vue'
import midtermEdit from './midtermEdit.vue'
import implementationPlanApi from '../../api/implementationPlanApi'
import coverApi from '../../api/cover'
import sysConfigApi from '@/api/sysConfig.js'
import revisionRecord from './groupImplementationPlan/revisionRecord.vue'
import advancedSearch from './advancedSearch.vue'
import addKeyTask from './groupImplementationPlan/addKeyTask.vue'
import taskDetail from './groupImplementationPlan/taskDetail.vue'
import startTask from './groupImplementationPlan/startTask.vue'
import exportTab from './groupImplementationPlan/exportTab.vue'
import bathSubmit from './groupImplementationPlan/bathSubmit.vue'
import { approvalMix } from '@/views/todoCenter/myApproval/approval-mix'
import tableColumnSetting from '@/mixin/tableColumnSetting'
import diffrentQuarterConfirm from './diffrentQuarterConfirm'
import {
  ALL_DATA_FLAG_LIST,
  ALL_DATA_FLAG_NEW,
  QUARTER_IS_SAME,
  QUARTER_IS_NOT_SAME
} from './const.js'
import permission from '@/mixin/permission'

export default {
  name: 'groupPlanData',
  components: {
    uploadFile
  },
  mixins: [approvalMix, tableColumnSetting, permission],
  props: {
    createbtnShow: {
      type: Boolean,
      default: false
    },
    code: {
      type: String,
      detault: ''
    },
    parentCode: {
      type: String,
      detault: ''
    },
    uploadUrl: {
      type: String,
      detault: ''
    },
    fromPage: {
      type: String,
      default: 'creater'
    },
     bussinessCode: {
       type: String,
      default: ''
    }
  },
  data() {
    return {
      departList,
      completeStatus,
      writePermission: true,
      allDataFlagList: ALL_DATA_FLAG_LIST,
      menuNo: this.fromPage == 'creater' ? 'group-implementation-plan' : 'summary-implementation-plan',
      useApiGetData: true,
      searchForm: {
        stype: '',  //大类
        mtype: '', //小类
        highTask: '',
        dpart: [],
        isFinished: '',
        self: this
      },
      planLevels: [],
      businessUnit: [],
      categoryInitiatives: [],//大类
      detailsInitiatives: [], //小类
      tableData:[],
      pageTableConfig: {
        loadDataFn: this.getServiceList.bind(this),
        columns: groupPlanDataColumns.bind(this)(),
        autoFirst: false, //默认 就是 false, 要配置在这里 
        onSelectionChange: this.onSelectionChange,
        border:true,
        pageSize: 100
      },
      columnList: this.fromPage != 'creater' ? this.deleteField(groupColumnList, 'wfStatusName') : groupColumnList,
      ids:[],
    }
  },

  computed: {
    createDisabled() {
      if (this.writePermission === false) {
        return true
      } else {
        return false
      }
    },

    submitDisabled() {
      if (this.writePermission === false) {
        return true
      } else {
        return false
      }
    },

    initDisabled(){
      if (this.writePermission === true && this.tableData?.length) {
        return false
      } else {
        return true
      }
    }
  },

  watch: {
    'searchForm.stype': {
      handler(val) {
        if (!val) {
          this.detailsInitiatives = []
          this.searchForm.mtype = ''
        }
      }
    }
  },

  methods: {
    //中期修改
    midtermEdit(row) {
      let code = this.createbtnShow ? this.searchForm.code : this.code
      new this.$sidelipPage(
        midtermEdit,
        {
          props: {
            id: row.id || '',
            code: code,
            parentCode: this.parentCode,
            Isedit: true,
            midtermEdit: true,
            dataStatus: Number(row.wfStatus) || 3,
            fromPage: this.fromPage,
            writePermission: this.writePermission
          },
        },
        data => {
          let { pageNum } = this.$refs['valueSetTable'].param
          data && this.searchValueSet(pageNum)
        }
      )
    },

    //获取大类
    getGroupTypeList(){
      coverApi.getGroupType({}).then(res => {
        if(res?.data?.code == 200 && res.data?.data?.length){
          this.categoryInitiatives = res.data.data
        }
        else{
          this.categoryInitiatives = []
        }
      })
    },

    init() {
      this.getGroupTypeList()
      // if (this.useApiGetData) {
      //   coverApi.getRptReportTrgnodePList({reportName: "数字化转型专项实施方案任务表"}).then(res => {
      //     this.planLevels = res.data.data
      //     if (this.fromPage != 'creater') {
      //       this.searchForm.code = this.bussinessCode
      //     }
      //     this.$nextTick(() => {
      //       this.searchValueSet()
      //     })
      //   })
      //   this.categoryInitiatives = categoryInitiatives
      //   this.searchForm.stype = ''
      // } else {
      //   this.planLevels = planLevel
      //   if (this.createbtnShow) {
      //     this.searchForm.stype = ''
      //   } else {
      //     if (this.bussinessCode) {
      //       this.searchForm.code = this.bussinessCode
      //       this.categoryInitiatives = this.planLevels.find(item => item.vsiValue == this.bussinessCode) ?  this.planLevels.find(item => item.vsiValue == this.bussinessCode).children : []
      //       this.detailsInitiatives = []
      //     }
      //   }
      //   this.searchValueSet()
      // }
      this.searchValueSet()
    },

    url(type, pathname) {
      return window.RPConfig[type] + pathname;
    },

    exportFun(row) {
      // 导出
      coverApi.downLoadFun({url: this.url('itShare', `/wfRptPlantask/listExport?id=${row.id}&trg_node&stype&mtype&task_code`)})
    },

    midterDeleteFun(params) {
      let idList = []
      if (Array.isArray(params)) {
        idList = [...params]
      } else if (params.id) {
        idList.push(params.id)
      }
       this.$confirm({
          title:"提交",
          content: "是否删除该实施方案任务表？"
        }).then(()=>{
          coverApi.coverDeleteMidtermData({
            type: this.fromPage,
            data: idList
          }).then((result) => {
            if(result.data.code == 200){
              this.$Message.success({
                content: '删除成功',
                duration: 3
              })
            } else {
              this.$Message.error({
                content: result.data.msg || '删除失败',
                duration: 3
            })
          }
            this.searchValueSet()
          })
        })
    },
    uploadSuccess(data) {
      if (data.code == QUARTER_IS_SAME) {
        this.searchValueSet()
      } else if (data.code == QUARTER_IS_NOT_SAME) {
        this.diffrentQuarterConfirm(data)
      }
    },
    diffrentQuarterConfirm(data) {
      new this.$pageModal(
        diffrentQuarterConfirm,
        {
          props: {
            fromAction: 'import',
            data
          }
        },
        (data) => {
          if (data) {
            let actionSource = data.actionSource
            let msg = ''
            if (actionSource == 'NotModifyAndSubmit') {
              msg = '导入成功'
              //  "excel导入方式 0-保持并提交 1-修改并提交"
              data.optType = '0'
            } else if (actionSource == 'ModifyAndSubmit') {
              msg = '修改季度导入成功'
              //  "excel导入方式 0-保持并提交 1-修改并提交"
              data.optType = '1'
            }
            this.confirmUpload(data, msg)
          }
        }
      );
    },
    confirmUpload(data, msg) {
      // this.disabledAction = true
        coverApi.confirmUpload({
          cacheDataId: data.cacheDataId,
          optType: data.optType
        }).then(res => {
          if(res.data.code == 200) {
            this.$Message.success({
              content: msg,
              duration: 3
            });
            this.searchValueSet()
          } else {
            this.$Message.error({
              content: res.data.msg || '操作失败',
              duration: 3
            });
          }
          this.$emit('Close', true)
        }).finally(() => {
          // this.disabledAction = false
        })
    },
    codeChange(list) {
      if (!this.useApiGetData) {
        this.categoryInitiatives = list.children
        this.searchForm.stype = ''
        this.detailsInitiatives = []
        this.searchForm.mtype = ''
      }
    },

    //选择大类，获取小类
    stypeChange(item) {
      // this.detailsInitiatives = list.children
      this.searchForm.mtype = '';
      this.getGroupMtypeList(item)
    },

    //获取小类
    getGroupMtypeList(item){
      coverApi.getGroupMtype({code:item.key}).then(res => {
        if(res?.data?.code == 200 && res.data?.data?.length){
          this.detailsInitiatives = res.data.data
        }
        else{
          this.detailsInitiatives = []
        }
      })
    },

    //查看详情
    goDetail(row) {
      let code = this.createbtnShow ? this.searchForm.code : this.code
       new this.$pageModal(
        taskDetail,
        {
          props: {
            mode:"look",
            id: row.id || '',
            categoryInitiatives: this.categoryInitiatives,
            disabledPage: true,
            code: code,
            parentCode: this.parentCode,
            fromPage: this.fromPage,
            dataStatus: Number(row.wfStatus) || 3,
          },
        },
        data => {
          data && this.searchValueSet()
        }
      )
    },

    //更新任务
    goUpdate(row) {
      let code = this.createbtnShow ? this.searchForm.code : this.code
       new this.$pageModal(
        taskDetail,
        {
          props: {
            mode:"update",
            id: row.id || '',
            categoryInitiatives: this.categoryInitiatives,
            disabledPage: true,
            code: code,
            parentCode: this.parentCode,
            fromPage: this.fromPage,
            dataStatus: Number(row.wfStatus) || 3,
          },
        },
        data => {
          data && this.searchValueSet()
        }
      )
    },

    goUpdateProgress(row) {
      let params = {
           taskCode: row.taskCode,
           trgNode: row.trgNode,
           stype: '',
           mtype: '',
           currentPage: 1,//当前页码
           pageSize: 100, //每页条数
           sortOrderBy: 'DESC',
           sortPropName: 'create_time'
      }
       coverApi.getGroupTableList({
        data: params,
        type: this.fromPage
       }).then( res => {
          let { records } = res.data.data
          if (Array.isArray(records) && records.length == 1) {
            this.goPlanCreatePage(records)
          } else {
            let content = '您选中的数据可能已经被删除，请刷新页面再次确认'
            if (records.length > 0) {
              content = '根据编码查询您选中的数据有重复，请先处理数据问题'
            }
            this.$Message.error({
                content,
                duration: 3
            })
          }
        })
    },

    //流程记录
    revisionRecord(row) {
      new this.$pageModal(
        revisionRecord,
        {
          props: {
            taskId: row.id
          }
        },
      );
    },

    //驳回
    goReject(){
      this.$confirm({
        title:"驳回",
        content: "是否驳回该实施方案任务表？"
      }).then(()=>{
        // coverApi.deleteTask(idList).then((result) => {
        //   if(result.data.code == 200){
        //     this.$Message.success({
        //       content: '驳回成功',
        //       duration: 3
        //     })
        //   } else {
        //     this.$Message.error({
        //       content: result.data.msg || '驳回失败',
        //       duration: 3
        //   })
        // }
        //   this.searchValueSet()
        // })
      })
    },

    //管理员编辑重点任务
    goEdit(row) {
      new this.$pageModal(
        addKeyTask,
        {
          props: {
            id: row.id || '',
            isEdit: true,
            categoryInitiatives: this.categoryInitiatives,
            dataStatus: Number(row.wfStatus) || 3,
            fromPage: this.fromPage,
            writePermission: this.writePermission
          },
        },
        data => {
          let { pageNum } = this.$refs['valueSetTable'].param
          data && this.searchValueSet(pageNum)
        }
      )
    },

    //管理员新增重点任务
    goPlanCreatePage(associationData){
      // if (!Array.isArray(associationData)) {
      //   associationData = []
      // }
      // new this.$sidelipPage(
      //   groupPlanEditAndDetail,
      //   {
      //     props: {
      //       code: '',
      //       parentCode: this.parentCode,
      //       fromPage: this.fromPage,
      //       associationData,
      //       fromAction: 'updateProgress'
      //     },
      //   },
      //   data => {
      //     data && this.searchValueSet()
      //   }
      // )
      
      new this.$pageModal(
        addKeyTask,
        {
          props: {
            isEdit: false,
            advanceSearchForm: this.searchForm,
            categoryInitiatives: this.categoryInitiatives,
            detailsInitiatives: this.detailsInitiatives,
            useApiGetData: this.useApiGetData,
            createbtnShow: this.createbtnShow,
            allDataFlagList: this.allDataFlagList,
            fromPage: this.fromPage
          }
        },
        data => {
          console.log(data,"232123")
          if (data) {
            // this.searchForm = data
            // let category = this.categoryInitiatives.find(item => item.vsiValue == this.searchForm.stype)
            // if (category) {
            //   this.detailsInitiatives = category.children
            // }
            this.searchValueSet()
          }
        }
      )
    },

    //获取表格数据
    getServiceList: tableObj => {
      let { responseProcess, param } = tableObj
      let { pageNum, pageSize,stype,mtype,highTask,dpart,isFinished,self } = param
      let params = {
        stype,
        mtype,
        highTask,
        dpart,
        isFinished,
        currentPage:  pageNum,//当前页码
        pageSize: pageSize //每页条数
      }
      coverApi.getGroupTableList({
      type: param.fromPage,
      data: params
      }).then(res => {
        if(res.data.code == 200) {
          let {current, pages, size, total, records } = res.data.data;
          self.tableData = records;
          if(records && records.length) {
            records.forEach(element => {
              element.wfStatusName = PROCESS_STATUS_MAP[element.wfStatus]
              element.importance = importist.find(ele => ele.key == element.importance)?.value;
              element.isFinished = completeStatus.find(ele => ele.key == element.isFinished)?.value;
              element.stype = self.categoryInitiatives.find(ele => ele.key == element.stype)?.value;
              element.dpart = departList.find(ele => ele.key == element.dpart)?.value;
            });
          }
          responseProcess({
            pageNum:Number(current),
            pageSize: Number(size),
            pages:Number(pages),
            records: records || [],
            total: Number(total),
          });
        } else {
          self.$Message.error({
            content: res.data.msg || '操作失败',
            duration: 3
          })
        }
        self.ids = []
      })
    },
    //搜索
    searchValueSet(pageNum = null) {
      this.$refs['valueSetTable'].load(this.searchForm, pageNum)
    },

    advancedSearch(){
      new this.$pageModal(
        advancedSearch,
        {
          props: {
            advanceSearchForm: this.searchForm,
            planLevels: this.planLevels,
            categoryInitiatives: this.categoryInitiatives,
            detailsInitiatives: this.detailsInitiatives,
            useApiGetData: this.useApiGetData,
            createbtnShow: this.createbtnShow,
            allDataFlagList: this.allDataFlagList,
            fromPage: this.fromPage,
          }
        },
        (data) => {
          if (data){
            this.searchForm = data
            let category = this.categoryInitiatives.find(item => item.vsiValue == this.searchForm.stype)
            if (category) {
              this.detailsInitiatives = category.children
            }
            this.searchValueSet()
          }
        }
      );
    },
    
    //勾选checkbox
    onSelectionChange(selection) {
      this.ids = []
        selection.forEach(element => {
        // console.log(element)
        this.ids.push({
          id: element.id,
          wfStatus: element.wfStatus,
          taskQuarter: element.taskQuarter
        })
      });
    },

    // 批量导出
    batchExport () {
      new this.$pageModal(
        exportTab,
        {
          props: {
            idList:this.ids
          },
        },
        data => {
          this.searchValueSet()
        }
      )
    },

    // 批量删除
    batchDel () {
      if(this.ids.length === 0) {
        this.$Message.error({
          content: '请选择数据后再进行操作',
          duration: 3
        })
        return
      }
      const idList = []
      this.ids.forEach(item => {
        idList.push(item.id)
      })
      if(idList.length > 0) {
        this.deleteFun(idList)
      }
    },

    deleteFun(params) {
      let idList = []
      if (Array.isArray(params)) {
        idList = [...params]
      } else if (params.id) {
        idList.push(params.id)
      }
       this.$confirm({
          title:"提交",
          content: "是否删除该实施方案任务表？"
        }).then(()=>{
          coverApi.deleteTask(idList).then((result) => {
            if(result.data.code == 200){
              this.$Message.success({
                content: '删除成功',
                duration: 3
              })
            } else {
              this.$Message.error({
                content: result.data.msg || '删除失败',
                duration: 3
            })
          }
            this.searchValueSet()
          })
        })
    },

    //汇总审批提交
    summaryAppSubmit(){
      this.$confirm({
        title:"提交汇总审批",
        content: "确认提交汇总审批？"
      }).then(()=>{
        coverApi.summaryAppSubmit().then(res => {
          if(res?.data?.code == 200){
            this.$Message.success({
              content: res?.data?.data || "汇总审批提交成功",
              duration: 3
            });
          }
          else{
            this.$Message.error({
              content: res?.data?.msg || "汇总审批提交失败",
              duration: 3
            });
          }
          this.searchValueSet()
        })
      })
    },

    // 批量提交
    batchSubmit() {
      if(!this.ids?.length) {
        this.$Message.error({
          content: '请选择数据后再进行操作',
          duration: 3
        })
        return
      }
      new this.$pageModal(
        bathSubmit,
        {
          props: {
            idList:this.ids,
            fromPage: this.fromPage
          }
        },
        data => {
          if (data) {
            this.searchValueSet()
          }
        }
      )
    },

    //初始化
    initTask(){
      coverApi.initCheckTask().then(res => {
        if(res?.data?.code == 200){
          this.$Message.success({
            content: res?.data?.data || "初始化成功",
            duration: 3
          });
        }
        else{
          this.$Message.error({
            content: res?.data?.msg || "初始化失败",
            duration: 3
          });
        }
        this.searchValueSet()
      })
    },

    //发起任务
    startTask(){
      if(this.ids.length === 0) {
        this.$Message.error({
          content: '请选择数据后再进行操作',
          duration: 3
        })
        return
      }
      new this.$pageModal(
        startTask,
        {
          props: {
            idList:this.ids,
            advanceSearchForm: this.searchForm,
            planLevels: this.planLevels,
            categoryInitiatives: this.categoryInitiatives,
            detailsInitiatives: this.detailsInitiatives,
            useApiGetData: this.useApiGetData,
            createbtnShow: this.createbtnShow,
            allDataFlagList: this.allDataFlagList,
            fromPage: this.fromPage
          }
        },
        data => {
          if (data) {
            this.searchValueSet()
          }
        }
      )
    }
  }
}
</script>
<style lang="less" scoped>
/deep/.table-bar button:last-child{
   color:#ffffff;
    background-color: #ff6f4b;
    border-color: #ff6f4b;
}

/deep/ .handle-cus{
  font-size: 18px;
  &:hover{
    color: #ff6f4b;
    cursor: pointer;
  }
}

</style>
